Passed
Pull Request — master (#229)
by
unknown
02:11
created

UpdateContactCommandHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 32
dl 0
loc 44
c 0
b 0
f 0
rs 10

1 Function

Rating   Name   Duplication   Size   Complexity  
B execute 0 34 5
1
import { CommandHandler } from '@nestjs/cqrs';
2
import { Inject } from '@nestjs/common';
3
import { UpdateContactCommand } from './UpdateContactCommand';
4
import { IContactRepository } from 'src/Domain/Contact/Repository/IContactRepository';
5
import { ContactNotFoundException } from 'src/Domain/Contact/Exception/ContactNotFoundException';
6
import { IsContactEmpty } from 'src/Domain/Contact/Specification/IsContactEmpty';
7
import { EmptyContactException } from 'src/Domain/Contact/Exception/EmptyContactException';
8
import { IUserRepository } from 'src/Domain/HumanResource/User/Repository/IUserRepository';
9
import { UserNotFoundException } from 'src/Domain/HumanResource/User/Exception/UserNotFoundException';
10
11
@CommandHandler(UpdateContactCommand)
12
export class UpdateContactCommandHandler {
13
  constructor(
14
    @Inject('IContactRepository')
15
    private readonly contactRepository: IContactRepository,
16
    @Inject('IUserRepository')
17
    private readonly userRepository: IUserRepository,
18
    private readonly isContactEmpty: IsContactEmpty
19
  ) {}
20
21
  public async execute(command: UpdateContactCommand): Promise<void> {
22
    const {
23
      id,
24
      firstName,
25
      lastName,
26
      company,
27
      email,
28
      phoneNumber,
29
      notes,
30
      contactedById
31
    } = command;
32
33
    const contact = await this.contactRepository.findOneById(id);
34
35
    if (!contact) {
36
      throw new ContactNotFoundException();
37
    }
38
39
    if (this.isContactEmpty.isSatisfiedBy(firstName, lastName, company)) {
40
      throw new EmptyContactException();
41
    }
42
43
    let contactedBy = null;
44
    if (contactedById) {
45
      contactedBy = await this.userRepository.findOneById(contactedById);
46
      if (!contactedBy) {
47
        throw new UserNotFoundException();
48
      }
49
    }
50
51
    contact.update(firstName, lastName, company, email, phoneNumber, notes, contactedBy);
52
53
    await this.contactRepository.save(contact);
54
  }
55
}
56